const util = require('util');
const debug = util.debuglog('oil-game:welfare:action');

const {
  Msg,
  MoneyType,
} = require("./consts");
const {
  createPrizeList,    //生成福利时刻奖品列表
  createOilPumpCoins,   //生成油泵的随机金币
  createOilPumpResult,    //生成油泵奖励结果
} = require("./util");
const {
  deliverChest,   //宝箱增加消息推送
} = require("./push");
const {
  getUserInfo,    //获取当前用户
  savePrize,    //保存当前福利时刻结果
  getPrize,   //获取用户福利时刻结果
  addWelfareOil,    //更新用户福利抽奖累计石油
} = require("./cache");
const {
  addOil,   //增加石油
  addCoins,   //增加金币
} = require("./api");

//首页油泵用户抽奖
exports.indexOilPump = async function(session){
  //获取奖励结果
  let prizeResult = createOilPumpResult();
  //需要返回给客户端的数据
  let result = {};
  switch(prizeResult.type){
    case "secretTime":    //神秘时刻
      setTimeout(()=>{
        //宝箱增加消息推送
        deliverChest.call(this, session);
      }, 1000);
      result = { type: "secretTime"}
      break;
    case "largeCoins":    //大量金币
      let {coins: coins1, showCoins: showCoins1} = createOilPumpCoins(prizeResult);
      //给用户增加金币
      await addCoins.call(this, session, coins1);
      //返回客户端结果
      result = { type: "large_coins", showCoins: showCoins1 }
      break;
    case "fewCoins":    //少量金币
      let { coins: coins2, showCoins: showCoins2 } = createOilPumpCoins(prizeResult);
      //给用户增加金币
      await addCoins.call(this, session, coins2);
      //返回客户端结果
      result = { type: "few_coins", showCoins: showCoins2 }
      break;
    case "nothing":    //无奖励
      result = { type: "nothing" }
      break;
  }

  return result;
}

//福利时刻用户抽奖
exports.welfare = async function(session){
  let { uid } = session;
  if (!uid) throw new Error(Msg.MISSING_PARAMETER);
  //获取当前用户
  let user = await getUserInfo.call(this, uid);
  //需要返回的奖品
  let prizeList = createPrizeList(user.welfare_oil);
  //将奖品保存到数据库
  await savePrize.call(this, uid, prizeList);
  return prizeList;
}

// 点击获取奖品
exports.getPrize = async function(session, msg){
  let { id } = msg;
  let { uid } = session;
  if (!uid || !id) throw new Error(Msg.MISSING_PARAMETER);
  //获取抽奖结果
  let prizeList = await getPrize.call(this, uid);
  if(prizeList.length < 1) throw new Error("没有抽奖信息")
  //当前所有结果
  let prizeInfo = prizeList[id];
  if(!prizeInfo) throw new Error("奖品ID错误")

  switch(prizeInfo.type){
    case MoneyType.OIL:
      let num = prizeInfo.value;
      //更新用户累计石油
      await addWelfareOil.call(this, uid, num)
      //增加石油
      await addOil.call(this, session, num);
    case MoneyType.GOLD:
      //增加金币
      await addCoins.call(this, session, num);
  }
}
